from rest_framework import serializers

from MirrorCore.models.Collection import Collection
from MirrorCore.models.Content import Article
from MirrorCore.serializers.BadgeSeriralizer import BadgeSerializer, ArticleBadgeSerializer
from MirrorCore.serializers.CollectionSerializer import CollectionSerializer, CollectionForOtherSerializer

from MirrorCore.serializers.utils import TimestampField



class ArticleSerializer(serializers.ModelSerializer):
    # author = serializers.CharField(source='author.username',read_only=True)
    collection = CollectionSerializer(read_only=True)
    # collection对应id，用于更新
    collection_id = serializers.IntegerField(write_only=True, allow_null=True, required=False)

    badges = ArticleBadgeSerializer(many=True,read_only=True)
    create_time = TimestampField(required=False)
    update_time = TimestampField(required=False,read_only=True)
    author_nickname = serializers.CharField(source='author.nickname', read_only=True)
    is_active = serializers.BooleanField(allow_null=True,required=False)

    class Meta:
        model = Article
        fields = ['id', 'title', 'brief', 'collection','collection_id', 'badges', 'content', 'author', 'author_nickname','create_time', 'update_time',"is_active"]

    def create(self, validated_data):
        res = Article.objects.create(**validated_data)
        print(res)
        return res

    def update(self, instance, validated_data):
        return super().update(instance, validated_data)

    # def update(self, instance, validated_data):
    #     print(validated_data)
    #     """
    #         valiedate_data 是经处理的有效字段，正如其名
    #     """
    #     instance.title = validated_data.get('title', instance.title)
    #     instance.brief = validated_data.get('brief', instance.brief)
    #     instance.content = validated_data.get('content', instance.content)
    #
    #     instance.save()
    #     return instance


    def validate(self, attrs):
        return super().validate(attrs)
